home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / rfc822.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-29  |  32KB  |  1,150 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. """RFC 2822 message manipulation.
  5.  
  6. Note: This is only a very rough sketch of a full RFC-822 parser; in particular
  7. the tokenizing of addresses does not adhere to all the quoting rules.
  8.  
  9. Note: RFC 2822 is a long awaited update to RFC 822.  This module should
  10. conform to RFC 2822, and is thus mis-named (it's not worth renaming it).  Some
  11. effort at RFC 2822 updates have been made, but a thorough audit has not been
  12. performed.  Consider any RFC 2822 non-conformance to be a bug.
  13.  
  14.     RFC 2822: http://www.faqs.org/rfcs/rfc2822.html
  15.     RFC 822 : http://www.faqs.org/rfcs/rfc822.html (obsolete)
  16.  
  17. Directions for use:
  18.  
  19. To create a Message object: first open a file, e.g.:
  20.  
  21.   fp = open(file, 'r')
  22.  
  23. You can use any other legal way of getting an open file object, e.g. use
  24. sys.stdin or call os.popen().  Then pass the open file object to the Message()
  25. constructor:
  26.  
  27.   m = Message(fp)
  28.  
  29. This class can work with any input object that supports a readline method.  If
  30. the input object has seek and tell capability, the rewindbody method will
  31. work; also illegal lines will be pushed back onto the input stream.  If the
  32. input object lacks seek but has an `unread' method that can push back a line
  33. of input, Message will use that to push back illegal lines.  Thus this class
  34. can be used to parse messages coming from a buffered stream.
  35.  
  36. The optional `seekable' argument is provided as a workaround for certain stdio
  37. libraries in which tell() discards buffered data before discovering that the
  38. lseek() system call doesn't work.  For maximum portability, you should set the
  39. seekable argument to zero to prevent that initial \\code{tell} when passing in
  40. an unseekable object such as a a file object created from a socket object.  If
  41. it is 1 on entry -- which it is by default -- the tell() method of the open
  42. file object is called once; if this raises an exception, seekable is reset to
  43. 0.  For other nonzero values of seekable, this test is not made.
  44.  
  45. To get the text of a particular header there are several methods:
  46.  
  47.   str = m.getheader(name)
  48.   str = m.getrawheader(name)
  49.  
  50. where name is the name of the header, e.g. 'Subject'.  The difference is that
  51. getheader() strips the leading and trailing whitespace, while getrawheader()
  52. doesn't.  Both functions retain embedded whitespace (including newlines)
  53. exactly as they are specified in the header, and leave the case of the text
  54. unchanged.
  55.  
  56. For addresses and address lists there are functions
  57.  
  58.   realname, mailaddress = m.getaddr(name)
  59.   list = m.getaddrlist(name)
  60.  
  61. where the latter returns a list of (realname, mailaddr) tuples.
  62.  
  63. There is also a method
  64.  
  65.   time = m.getdate(name)
  66.  
  67. which parses a Date-like field and returns a time-compatible tuple,
  68. i.e. a tuple such as returned by time.localtime() or accepted by
  69. time.mktime().
  70.  
  71. See the class definition for lower level access methods.
  72.  
  73. There are also some utility functions here.
  74. """
  75. import time
  76. __all__ = [
  77.     'Message',
  78.     'AddressList',
  79.     'parsedate',
  80.     'parsedate_tz',
  81.     'mktime_tz']
  82. _blanklines = ('\r\n', '\n')
  83.  
  84. class Message:
  85.     '''Represents a single RFC 2822-compliant message.'''
  86.     
  87.     def __init__(self, fp, seekable = 1):
  88.         '''Initialize the class instance and read the headers.'''
  89.         if seekable == 1:
  90.             
  91.             try:
  92.                 fp.tell()
  93.             except (AttributeError, IOError):
  94.                 seekable = 0
  95.             except:
  96.                 None<EXCEPTION MATCH>(AttributeError, IOError)
  97.             
  98.  
  99.         None<EXCEPTION MATCH>(AttributeError, IOError)
  100.         self.fp = fp
  101.         self.seekable = seekable
  102.         self.startofheaders = None
  103.         self.startofbody = None
  104.         if self.seekable:
  105.             
  106.             try:
  107.                 self.startofheaders = self.fp.tell()
  108.             except IOError:
  109.                 self.seekable = 0
  110.             except:
  111.                 None<EXCEPTION MATCH>IOError
  112.             
  113.  
  114.         None<EXCEPTION MATCH>IOError
  115.         self.readheaders()
  116.         if self.seekable:
  117.             
  118.             try:
  119.                 self.startofbody = self.fp.tell()
  120.             except IOError:
  121.                 self.seekable = 0
  122.             except:
  123.                 None<EXCEPTION MATCH>IOError
  124.             
  125.  
  126.         None<EXCEPTION MATCH>IOError
  127.  
  128.     
  129.     def rewindbody(self):
  130.         '''Rewind the file to the start of the body (if seekable).'''
  131.         if not self.seekable:
  132.             raise IOError, 'unseekable file'
  133.         
  134.         self.fp.seek(self.startofbody)
  135.  
  136.     
  137.     def readheaders(self):
  138.         '''Read header lines.
  139.  
  140.         Read header lines up to the entirely blank line that terminates them.
  141.         The (normally blank) line that ends the headers is skipped, but not
  142.         included in the returned list.  If a non-header line ends the headers,
  143.         (which is an error), an attempt is made to backspace over it; it is
  144.         never included in the returned list.
  145.  
  146.         The variable self.status is set to the empty string if all went well,
  147.         otherwise it is an error message.  The variable self.headers is a
  148.         completely uninterpreted list of lines contained in the header (so
  149.         printing them will reproduce the header exactly as it appears in the
  150.         file).
  151.         '''
  152.         self.dict = { }
  153.         self.unixfrom = ''
  154.         self.headers = lst = []
  155.         self.status = ''
  156.         headerseen = ''
  157.         firstline = 1
  158.         startofline = None
  159.         unread = None
  160.         tell = None
  161.         if hasattr(self.fp, 'unread'):
  162.             unread = self.fp.unread
  163.         elif self.seekable:
  164.             tell = self.fp.tell
  165.         
  166.         while tell:
  167.             
  168.             try:
  169.                 startofline = tell()
  170.             except IOError:
  171.                 startofline = None
  172.                 tell = None
  173.                 self.seekable = 0
  174.             except:
  175.                 None<EXCEPTION MATCH>IOError
  176.             
  177.  
  178.             None<EXCEPTION MATCH>IOError
  179.             line = self.fp.readline()
  180.             if not line:
  181.                 self.status = 'EOF in headers'
  182.                 break
  183.             
  184.         if firstline and line.startswith('From '):
  185.             self.unixfrom = self.unixfrom + line
  186.             continue
  187.         
  188.         firstline = 0
  189.         if headerseen and line[0] in ' \t':
  190.             lst.append(line)
  191.             x = self.dict[headerseen] + '\n ' + line.strip()
  192.             self.dict[headerseen] = x.strip()
  193.             continue
  194.         elif self.iscomment(line):
  195.             continue
  196.         elif self.islast(line):
  197.             break
  198.         
  199.         headerseen = self.isheader(line)
  200.         if headerseen:
  201.             lst.append(line)
  202.             self.dict[headerseen] = line[len(headerseen) + 1:].strip()
  203.             continue
  204.             continue
  205.         if not self.dict:
  206.             self.status = 'No headers'
  207.         else:
  208.             self.status = 'Non-header line where header expected'
  209.         if unread:
  210.             unread(line)
  211.         elif tell:
  212.             self.fp.seek(startofline)
  213.         else:
  214.             self.status = self.status + '; bad seek'
  215.         break
  216.         continue
  217.  
  218.     
  219.     def isheader(self, line):
  220.         '''Determine whether a given line is a legal header.
  221.  
  222.         This method should return the header name, suitably canonicalized.
  223.         You may override this method in order to use Message parsing on tagged
  224.         data in RFC 2822-like formats with special header formats.
  225.         '''
  226.         i = line.find(':')
  227.         if i > 0:
  228.             return line[:i].lower()
  229.         
  230.  
  231.     
  232.     def islast(self, line):
  233.         """Determine whether a line is a legal end of RFC 2822 headers.
  234.  
  235.         You may override this method if your application wants to bend the
  236.         rules, e.g. to strip trailing whitespace, or to recognize MH template
  237.         separators ('--------').  For convenience (e.g. for code reading from
  238.         sockets) a line consisting of \r
  239.  also matches.
  240.         """
  241.         return line in _blanklines
  242.  
  243.     
  244.     def iscomment(self, line):
  245.         '''Determine whether a line should be skipped entirely.
  246.  
  247.         You may override this method in order to use Message parsing on tagged
  248.         data in RFC 2822-like formats that support embedded comments or
  249.         free-text data.
  250.         '''
  251.         return False
  252.  
  253.     
  254.     def getallmatchingheaders(self, name):
  255.         '''Find all header lines matching a given header name.
  256.  
  257.         Look through the list of headers and find all lines matching a given
  258.         header name (and their continuation lines).  A list of the lines is
  259.         returned, without interpretation.  If the header does not occur, an
  260.         empty list is returned.  If the header occurs multiple times, all
  261.         occurrences are returned.  Case is not important in the header name.
  262.         '''
  263.         name = name.lower() + ':'
  264.         n = len(name)
  265.         lst = []
  266.         hit = 0
  267.         for line in self.headers:
  268.             if line[:n].lower() == name:
  269.                 hit = 1
  270.             elif not line[:1].isspace():
  271.                 hit = 0
  272.             
  273.             if hit:
  274.                 lst.append(line)
  275.                 continue
  276.         
  277.         return lst
  278.  
  279.     
  280.     def getfirstmatchingheader(self, name):
  281.         '''Get the first header line matching name.
  282.  
  283.         This is similar to getallmatchingheaders, but it returns only the
  284.         first matching header (and its continuation lines).
  285.         '''
  286.         name = name.lower() + ':'
  287.         n = len(name)
  288.         lst = []
  289.         hit = 0
  290.         for line in self.headers:
  291.             if hit:
  292.                 if not line[:1].isspace():
  293.                     break
  294.                 
  295.             elif line[:n].lower() == name:
  296.                 hit = 1
  297.             
  298.             if hit:
  299.                 lst.append(line)
  300.                 continue
  301.         
  302.         return lst
  303.  
  304.     
  305.     def getrawheader(self, name):
  306.         '''A higher-level interface to getfirstmatchingheader().
  307.  
  308.         Return a string containing the literal text of the header but with the
  309.         keyword stripped.  All leading, trailing and embedded whitespace is
  310.         kept in the string, however.  Return None if the header does not
  311.         occur.
  312.         '''
  313.         lst = self.getfirstmatchingheader(name)
  314.         if not lst:
  315.             return None
  316.         
  317.         lst[0] = lst[0][len(name) + 1:]
  318.         return ''.join(lst)
  319.  
  320.     
  321.     def getheader(self, name, default = None):
  322.         """Get the header value for a name.
  323.  
  324.         This is the normal interface: it returns a stripped version of the
  325.         header value for a given header name, or None if it doesn't exist.
  326.         This uses the dictionary version which finds the *last* such header.
  327.         """
  328.         return self.dict.get(name.lower(), default)
  329.  
  330.     get = getheader
  331.     
  332.     def getheaders(self, name):
  333.         '''Get all values for a header.
  334.  
  335.         This returns a list of values for headers given more than once; each
  336.         value in the result list is stripped in the same way as the result of
  337.         getheader().  If the header is not given, return an empty list.
  338.         '''
  339.         result = []
  340.         current = ''
  341.         have_header = 0
  342.         for s in self.getallmatchingheaders(name):
  343.             if s[0].isspace():
  344.                 if current:
  345.                     current = '%s\n %s' % (current, s.strip())
  346.                 else:
  347.                     current = s.strip()
  348.             current
  349.             if have_header:
  350.                 result.append(current)
  351.             
  352.             current = s[s.find(':') + 1:].strip()
  353.             have_header = 1
  354.         
  355.         if have_header:
  356.             result.append(current)
  357.         
  358.         return result
  359.  
  360.     
  361.     def getaddr(self, name):
  362.         """Get a single address from a header, as a tuple.
  363.  
  364.         An example return value:
  365.         ('Guido van Rossum', 'guido@cwi.nl')
  366.         """
  367.         alist = self.getaddrlist(name)
  368.         if alist:
  369.             return alist[0]
  370.         else:
  371.             return (None, None)
  372.  
  373.     
  374.     def getaddrlist(self, name):
  375.         '''Get a list of addresses from a header.
  376.  
  377.         Retrieves a list of addresses from a header, where each address is a
  378.         tuple as returned by getaddr().  Scans all named headers, so it works
  379.         properly with multiple To: or Cc: headers for example.
  380.         '''
  381.         raw = []
  382.         for h in self.getallmatchingheaders(name):
  383.             if h[0] in ' \t':
  384.                 raw.append(h)
  385.                 continue
  386.             if raw:
  387.                 raw.append(', ')
  388.             
  389.             i = h.find(':')
  390.             if i > 0:
  391.                 addr = h[i + 1:]
  392.             
  393.             raw.append(addr)
  394.         
  395.         alladdrs = ''.join(raw)
  396.         a = AddressList(alladdrs)
  397.         return a.addresslist
  398.  
  399.     
  400.     def getdate(self, name):
  401.         '''Retrieve a date field from a header.
  402.  
  403.         Retrieves a date field from the named header, returning a tuple
  404.         compatible with time.mktime().
  405.         '''
  406.         
  407.         try:
  408.             data = self[name]
  409.         except KeyError:
  410.             return None
  411.  
  412.         return parsedate(data)
  413.  
  414.     
  415.     def getdate_tz(self, name):
  416.         """Retrieve a date field from a header as a 10-tuple.
  417.  
  418.         The first 9 elements make up a tuple compatible with time.mktime(),
  419.         and the 10th is the offset of the poster's time zone from GMT/UTC.
  420.         """
  421.         
  422.         try:
  423.             data = self[name]
  424.         except KeyError:
  425.             return None
  426.  
  427.         return parsedate_tz(data)
  428.  
  429.     
  430.     def __len__(self):
  431.         '''Get the number of headers in a message.'''
  432.         return len(self.dict)
  433.  
  434.     
  435.     def __getitem__(self, name):
  436.         '''Get a specific header, as from a dictionary.'''
  437.         return self.dict[name.lower()]
  438.  
  439.     
  440.     def __setitem__(self, name, value):
  441.         '''Set the value of a header.
  442.  
  443.         Note: This is not a perfect inversion of __getitem__, because any
  444.         changed headers get stuck at the end of the raw-headers list rather
  445.         than where the altered header was.
  446.         '''
  447.         del self[name]
  448.         self.dict[name.lower()] = value
  449.         text = name + ': ' + value
  450.         for line in text.split('\n'):
  451.             self.headers.append(line + '\n')
  452.         
  453.  
  454.     
  455.     def __delitem__(self, name):
  456.         '''Delete all occurrences of a specific header, if it is present.'''
  457.         name = name.lower()
  458.         if name not in self.dict:
  459.             return None
  460.         
  461.         del self.dict[name]
  462.         name = name + ':'
  463.         n = len(name)
  464.         lst = []
  465.         hit = 0
  466.         for i in range(len(self.headers)):
  467.             line = self.headers[i]
  468.             if line[:n].lower() == name:
  469.                 hit = 1
  470.             elif not line[:1].isspace():
  471.                 hit = 0
  472.             
  473.             if hit:
  474.                 lst.append(i)
  475.                 continue
  476.         
  477.         for i in reversed(lst):
  478.             del self.headers[i]
  479.         
  480.  
  481.     
  482.     def setdefault(self, name, default = ''):
  483.         lowername = name.lower()
  484.         if lowername in self.dict:
  485.             return self.dict[lowername]
  486.         else:
  487.             text = name + ': ' + default
  488.             for line in text.split('\n'):
  489.                 self.headers.append(line + '\n')
  490.             
  491.             self.dict[lowername] = default
  492.             return default
  493.  
  494.     
  495.     def has_key(self, name):
  496.         '''Determine whether a message contains the named header.'''
  497.         return name.lower() in self.dict
  498.  
  499.     
  500.     def __contains__(self, name):
  501.         '''Determine whether a message contains the named header.'''
  502.         return name.lower() in self.dict
  503.  
  504.     
  505.     def __iter__(self):
  506.         return iter(self.dict)
  507.  
  508.     
  509.     def keys(self):
  510.         """Get all of a message's header field names."""
  511.         return self.dict.keys()
  512.  
  513.     
  514.     def values(self):
  515.         """Get all of a message's header field values."""
  516.         return self.dict.values()
  517.  
  518.     
  519.     def items(self):
  520.         """Get all of a message's headers.
  521.  
  522.         Returns a list of name, value tuples.
  523.         """
  524.         return self.dict.items()
  525.  
  526.     
  527.     def __str__(self):
  528.         return ''.join(self.headers)
  529.  
  530.  
  531.  
  532. def unquote(s):
  533.     '''Remove quotes from a string.'''
  534.     if len(s) > 1:
  535.         if s.startswith('"') and s.endswith('"'):
  536.             return s[1:-1].replace('\\\\', '\\').replace('\\"', '"')
  537.         
  538.         if s.startswith('<') and s.endswith('>'):
  539.             return s[1:-1]
  540.         
  541.     
  542.     return s
  543.  
  544.  
  545. def quote(s):
  546.     '''Add quotes around a string.'''
  547.     return s.replace('\\', '\\\\').replace('"', '\\"')
  548.  
  549.  
  550. def parseaddr(address):
  551.     '''Parse an address into a (realname, mailaddr) tuple.'''
  552.     a = AddressList(address)
  553.     lst = a.addresslist
  554.     if not lst:
  555.         return (None, None)
  556.     
  557.     return lst[0]
  558.  
  559.  
  560. class AddrlistClass:
  561.     '''Address parser class by Ben Escoto.
  562.  
  563.     To understand what this class does, it helps to have a copy of
  564.     RFC 2822 in front of you.
  565.  
  566.     http://www.faqs.org/rfcs/rfc2822.html
  567.  
  568.     Note: this class interface is deprecated and may be removed in the future.
  569.     Use rfc822.AddressList instead.
  570.     '''
  571.     
  572.     def __init__(self, field):
  573.         """Initialize a new instance.
  574.  
  575.         `field' is an unparsed address header field, containing one or more
  576.         addresses.
  577.         """
  578.         self.specials = '()<>@,:;."[]'
  579.         self.pos = 0
  580.         self.LWS = ' \t'
  581.         self.CR = '\r\n'
  582.         self.atomends = self.specials + self.LWS + self.CR
  583.         self.phraseends = self.atomends.replace('.', '')
  584.         self.field = field
  585.         self.commentlist = []
  586.  
  587.     
  588.     def gotonext(self):
  589.         '''Parse up to the start of the next address.'''
  590.         while self.pos < len(self.field):
  591.             if self.field[self.pos] in self.LWS + '\n\r':
  592.                 self.pos = self.pos + 1
  593.                 continue
  594.             if self.field[self.pos] == '(':
  595.                 self.commentlist.append(self.getcomment())
  596.                 continue
  597.             break
  598.  
  599.     
  600.     def getaddrlist(self):
  601.         '''Parse all addresses.
  602.  
  603.         Returns a list containing all of the addresses.
  604.         '''
  605.         result = []
  606.         ad = self.getaddress()
  607.         while ad:
  608.             result += ad
  609.             ad = self.getaddress()
  610.         return result
  611.  
  612.     
  613.     def getaddress(self):
  614.         '''Parse the next address.'''
  615.         self.commentlist = []
  616.         self.gotonext()
  617.         oldpos = self.pos
  618.         oldcl = self.commentlist
  619.         plist = self.getphraselist()
  620.         self.gotonext()
  621.         returnlist = []
  622.         if self.pos >= len(self.field):
  623.             if plist:
  624.                 returnlist = [
  625.                     (' '.join(self.commentlist), plist[0])]
  626.             
  627.         elif self.field[self.pos] in '.@':
  628.             self.pos = oldpos
  629.             self.commentlist = oldcl
  630.             addrspec = self.getaddrspec()
  631.             returnlist = [
  632.                 (' '.join(self.commentlist), addrspec)]
  633.         elif self.field[self.pos] == ':':
  634.             returnlist = []
  635.             fieldlen = len(self.field)
  636.             self.pos += 1
  637.             while self.pos < len(self.field):
  638.                 self.gotonext()
  639.                 returnlist = returnlist + self.getaddress()
  640.                 continue
  641.                 None if self.pos < fieldlen and self.field[self.pos] == ';' else self
  642.         elif self.field[self.pos] == '<':
  643.             routeaddr = self.getrouteaddr()
  644.             if self.commentlist:
  645.                 returnlist = [
  646.                     (' '.join(plist) + ' (' + ' '.join(self.commentlist) + ')', routeaddr)]
  647.             else:
  648.                 returnlist = [
  649.                     (' '.join(plist), routeaddr)]
  650.         elif plist:
  651.             returnlist = [
  652.                 (' '.join(self.commentlist), plist[0])]
  653.         elif self.field[self.pos] in self.specials:
  654.             self.pos += 1
  655.         
  656.         self.gotonext()
  657.         if self.pos < len(self.field) and self.field[self.pos] == ',':
  658.             self.pos += 1
  659.         
  660.         return returnlist
  661.  
  662.     
  663.     def getrouteaddr(self):
  664.         '''Parse a route address (Return-path value).
  665.  
  666.         This method just skips all the route stuff and returns the addrspec.
  667.         '''
  668.         if self.field[self.pos] != '<':
  669.             return None
  670.         
  671.         expectroute = 0
  672.         self.pos += 1
  673.         self.gotonext()
  674.         adlist = ''
  675.         while self.pos < len(self.field):
  676.             if expectroute:
  677.                 self.getdomain()
  678.                 expectroute = 0
  679.             elif self.field[self.pos] == '>':
  680.                 self.pos += 1
  681.                 break
  682.             elif self.field[self.pos] == '@':
  683.                 self.pos += 1
  684.                 expectroute = 1
  685.             elif self.field[self.pos] == ':':
  686.                 self.pos += 1
  687.             else:
  688.                 adlist = self.getaddrspec()
  689.                 self.pos += 1
  690.                 break
  691.             self.gotonext()
  692.             continue
  693.             self
  694.         return adlist
  695.  
  696.     
  697.     def getaddrspec(self):
  698.         '''Parse an RFC 2822 addr-spec.'''
  699.         aslist = []
  700.         self.gotonext()
  701.         while self.pos < len(self.field):
  702.             if self.field[self.pos] == '.':
  703.                 aslist.append('.')
  704.                 self.pos += 1
  705.             elif self.field[self.pos] == '"':
  706.                 aslist.append('"%s"' % self.getquote())
  707.             elif self.field[self.pos] in self.atomends:
  708.                 break
  709.             else:
  710.                 aslist.append(self.getatom())
  711.             self.gotonext()
  712.         if self.pos >= len(self.field) or self.field[self.pos] != '@':
  713.             return ''.join(aslist)
  714.         
  715.         aslist.append('@')
  716.         self.pos += 1
  717.         self.gotonext()
  718.         return ''.join(aslist) + self.getdomain()
  719.  
  720.     
  721.     def getdomain(self):
  722.         '''Get the complete domain name from an address.'''
  723.         sdlist = []
  724.         while self.pos < len(self.field):
  725.             if self.field[self.pos] in self.LWS:
  726.                 self.pos += 1
  727.                 continue
  728.             self
  729.             if self.field[self.pos] == '(':
  730.                 self.commentlist.append(self.getcomment())
  731.                 continue
  732.             None if self.field[self.pos] == '[' else self
  733.             if self.field[self.pos] in self.atomends:
  734.                 break
  735.                 continue
  736.             sdlist.append(self.getatom())
  737.         return ''.join(sdlist)
  738.  
  739.     
  740.     def getdelimited(self, beginchar, endchars, allowcomments = 1):
  741.         """Parse a header fragment delimited by special characters.
  742.  
  743.         `beginchar' is the start character for the fragment.  If self is not
  744.         looking at an instance of `beginchar' then getdelimited returns the
  745.         empty string.
  746.  
  747.         `endchars' is a sequence of allowable end-delimiting characters.
  748.         Parsing stops when one of these is encountered.
  749.  
  750.         If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed
  751.         within the parsed fragment.
  752.         """
  753.         if self.field[self.pos] != beginchar:
  754.             return ''
  755.         
  756.         slist = [
  757.             '']
  758.         quote = 0
  759.         self.pos += 1
  760.         while self.pos < len(self.field):
  761.             if quote == 1:
  762.                 slist.append(self.field[self.pos])
  763.                 quote = 0
  764.             elif self.field[self.pos] in endchars:
  765.                 self.pos += 1
  766.                 break
  767.             elif allowcomments and self.field[self.pos] == '(':
  768.                 slist.append(self.getcomment())
  769.                 continue
  770.             elif self.field[self.pos] == '\\':
  771.                 quote = 1
  772.             else:
  773.                 slist.append(self.field[self.pos])
  774.             self.pos += 1
  775.             continue
  776.             self
  777.         return ''.join(slist)
  778.  
  779.     
  780.     def getquote(self):
  781.         """Get a quote-delimited fragment from self's field."""
  782.         return self.getdelimited('"', '"\r', 0)
  783.  
  784.     
  785.     def getcomment(self):
  786.         """Get a parenthesis-delimited fragment from self's field."""
  787.         return self.getdelimited('(', ')\r', 1)
  788.  
  789.     
  790.     def getdomainliteral(self):
  791.         '''Parse an RFC 2822 domain-literal.'''
  792.         return '[%s]' % self.getdelimited('[', ']\r', 0)
  793.  
  794.     
  795.     def getatom(self, atomends = None):
  796.         """Parse an RFC 2822 atom.
  797.  
  798.         Optional atomends specifies a different set of end token delimiters
  799.         (the default is to use self.atomends).  This is used e.g. in
  800.         getphraselist() since phrase endings must not include the `.' (which
  801.         is legal in phrases)."""
  802.         atomlist = [
  803.             '']
  804.         if atomends is None:
  805.             atomends = self.atomends
  806.         
  807.         while self.pos < len(self.field):
  808.             if self.field[self.pos] in atomends:
  809.                 break
  810.             else:
  811.                 atomlist.append(self.field[self.pos])
  812.             self.pos += 1
  813.             continue
  814.             self
  815.         return ''.join(atomlist)
  816.  
  817.     
  818.     def getphraselist(self):
  819.         '''Parse a sequence of RFC 2822 phrases.
  820.  
  821.         A phrase is a sequence of words, which are in turn either RFC 2822
  822.         atoms or quoted-strings.  Phrases are canonicalized by squeezing all
  823.         runs of continuous whitespace into one space.
  824.         '''
  825.         plist = []
  826.         while self.pos < len(self.field):
  827.             if self.field[self.pos] in self.LWS:
  828.                 self.pos += 1
  829.                 continue
  830.             self
  831.             if self.field[self.pos] == '"':
  832.                 plist.append(self.getquote())
  833.                 continue
  834.             if self.field[self.pos] == '(':
  835.                 self.commentlist.append(self.getcomment())
  836.                 continue
  837.             if self.field[self.pos] in self.phraseends:
  838.                 break
  839.                 continue
  840.             plist.append(self.getatom(self.phraseends))
  841.         return plist
  842.  
  843.  
  844.  
  845. class AddressList(AddrlistClass):
  846.     '''An AddressList encapsulates a list of parsed RFC 2822 addresses.'''
  847.     
  848.     def __init__(self, field):
  849.         AddrlistClass.__init__(self, field)
  850.         if field:
  851.             self.addresslist = self.getaddrlist()
  852.         else:
  853.             self.addresslist = []
  854.  
  855.     
  856.     def __len__(self):
  857.         return len(self.addresslist)
  858.  
  859.     
  860.     def __str__(self):
  861.         return ', '.join(map(dump_address_pair, self.addresslist))
  862.  
  863.     
  864.     def __add__(self, other):
  865.         newaddr = AddressList(None)
  866.         newaddr.addresslist = self.addresslist[:]
  867.         for x in other.addresslist:
  868.             if x not in self.addresslist:
  869.                 newaddr.addresslist.append(x)
  870.                 continue
  871.         
  872.         return newaddr
  873.  
  874.     
  875.     def __iadd__(self, other):
  876.         for x in other.addresslist:
  877.             if x not in self.addresslist:
  878.                 self.addresslist.append(x)
  879.                 continue
  880.         
  881.         return self
  882.  
  883.     
  884.     def __sub__(self, other):
  885.         newaddr = AddressList(None)
  886.         for x in self.addresslist:
  887.             if x not in other.addresslist:
  888.                 newaddr.addresslist.append(x)
  889.                 continue
  890.         
  891.         return newaddr
  892.  
  893.     
  894.     def __isub__(self, other):
  895.         for x in other.addresslist:
  896.             if x in self.addresslist:
  897.                 self.addresslist.remove(x)
  898.                 continue
  899.         
  900.         return self
  901.  
  902.     
  903.     def __getitem__(self, index):
  904.         return self.addresslist[index]
  905.  
  906.  
  907.  
  908. def dump_address_pair(pair):
  909.     '''Dump a (name, address) pair in a canonicalized form.'''
  910.     if pair[0]:
  911.         return '"' + pair[0] + '" <' + pair[1] + '>'
  912.     else:
  913.         return pair[1]
  914.  
  915. _monthnames = [
  916.     'jan',
  917.     'feb',
  918.     'mar',
  919.     'apr',
  920.     'may',
  921.     'jun',
  922.     'jul',
  923.     'aug',
  924.     'sep',
  925.     'oct',
  926.     'nov',
  927.     'dec',
  928.     'january',
  929.     'february',
  930.     'march',
  931.     'april',
  932.     'may',
  933.     'june',
  934.     'july',
  935.     'august',
  936.     'september',
  937.     'october',
  938.     'november',
  939.     'december']
  940. _daynames = [
  941.     'mon',
  942.     'tue',
  943.     'wed',
  944.     'thu',
  945.     'fri',
  946.     'sat',
  947.     'sun']
  948. _timezones = {
  949.     'UT': 0,
  950.     'UTC': 0,
  951.     'GMT': 0,
  952.     'Z': 0,
  953.     'AST': -400,
  954.     'ADT': -300,
  955.     'EST': -500,
  956.     'EDT': -400,
  957.     'CST': -600,
  958.     'CDT': -500,
  959.     'MST': -700,
  960.     'MDT': -600,
  961.     'PST': -800,
  962.     'PDT': -700 }
  963.  
  964. def parsedate_tz(data):
  965.     '''Convert a date string to a time tuple.
  966.  
  967.     Accounts for military timezones.
  968.     '''
  969.     if not data:
  970.         return None
  971.     
  972.     data = data.split()
  973.     if data[0][-1] in (',', '.') or data[0].lower() in _daynames:
  974.         del data[0]
  975.     else:
  976.         i = data[0].rfind(',')
  977.         if i >= 0:
  978.             data[0] = data[0][i + 1:]
  979.         
  980.     if len(data) == 3:
  981.         stuff = data[0].split('-')
  982.         if len(stuff) == 3:
  983.             data = stuff + data[1:]
  984.         
  985.     
  986.     if len(data) == 4:
  987.         s = data[3]
  988.         i = s.find('+')
  989.         if i > 0:
  990.             data[3:] = [
  991.                 s[:i],
  992.                 s[i + 1:]]
  993.         else:
  994.             data.append('')
  995.     
  996.     if len(data) < 5:
  997.         return None
  998.     
  999.     data = data[:5]
  1000.     (dd, mm, yy, tm, tz) = data
  1001.     mm = mm.lower()
  1002.     if mm not in _monthnames:
  1003.         dd = mm
  1004.         mm = dd.lower()
  1005.         if mm not in _monthnames:
  1006.             return None
  1007.         
  1008.     
  1009.     mm = _monthnames.index(mm) + 1
  1010.     if mm > 12:
  1011.         mm = mm - 12
  1012.     
  1013.     if dd[-1] == ',':
  1014.         dd = dd[:-1]
  1015.     
  1016.     i = yy.find(':')
  1017.     if i > 0:
  1018.         yy = tm
  1019.         tm = yy
  1020.     
  1021.     if yy[-1] == ',':
  1022.         yy = yy[:-1]
  1023.     
  1024.     if not yy[0].isdigit():
  1025.         yy = tz
  1026.         tz = yy
  1027.     
  1028.     if tm[-1] == ',':
  1029.         tm = tm[:-1]
  1030.     
  1031.     tm = tm.split(':')
  1032.     if len(tm) == 2:
  1033.         (thh, tmm) = tm
  1034.         tss = '0'
  1035.     elif len(tm) == 3:
  1036.         (thh, tmm, tss) = tm
  1037.     else:
  1038.         return None
  1039.     
  1040.     try:
  1041.         yy = int(yy)
  1042.         dd = int(dd)
  1043.         thh = int(thh)
  1044.         tmm = int(tmm)
  1045.         tss = int(tss)
  1046.     except ValueError:
  1047.         return None
  1048.  
  1049.     tzoffset = None
  1050.     tz = tz.upper()
  1051.     if tz in _timezones:
  1052.         tzoffset = _timezones[tz]
  1053.     else:
  1054.         
  1055.         try:
  1056.             tzoffset = int(tz)
  1057.         except ValueError:
  1058.             pass
  1059.  
  1060.     if tzoffset:
  1061.         if tzoffset < 0:
  1062.             tzsign = -1
  1063.             tzoffset = -tzoffset
  1064.         else:
  1065.             tzsign = 1
  1066.         tzoffset = tzsign * ((tzoffset // 100) * 3600 + (tzoffset % 100) * 60)
  1067.     
  1068.     return (yy, mm, dd, thh, tmm, tss, 0, 1, 0, tzoffset)
  1069.  
  1070.  
  1071. def parsedate(data):
  1072.     '''Convert a time string to a time tuple.'''
  1073.     t = parsedate_tz(data)
  1074.     if t is None:
  1075.         return t
  1076.     
  1077.     return t[:9]
  1078.  
  1079.  
  1080. def mktime_tz(data):
  1081.     '''Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.'''
  1082.     if data[9] is None:
  1083.         return time.mktime(data[:8] + (-1,))
  1084.     else:
  1085.         t = time.mktime(data[:8] + (0,))
  1086.         return t - data[9] - time.timezone
  1087.  
  1088.  
  1089. def formatdate(timeval = None):
  1090.     """Returns time format preferred for Internet standards.
  1091.  
  1092.     Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
  1093.  
  1094.     According to RFC 1123, day and month names must always be in
  1095.     English.  If not for that, this code could use strftime().  It
  1096.     can't because strftime() honors the locale and could generated
  1097.     non-English names.
  1098.     """
  1099.     if timeval is None:
  1100.         timeval = time.time()
  1101.     
  1102.     timeval = time.gmtime(timeval)
  1103.     return '%s, %02d %s %04d %02d:%02d:%02d GMT' % (('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[timeval[6]], timeval[2], ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')[timeval[1] - 1], timeval[0], timeval[3], timeval[4], timeval[5])
  1104.  
  1105. if __name__ == '__main__':
  1106.     import sys
  1107.     import os
  1108.     file = os.path.join(os.environ['HOME'], 'Mail/inbox/1')
  1109.     if sys.argv[1:]:
  1110.         file = sys.argv[1]
  1111.     
  1112.     f = open(file, 'r')
  1113.     m = Message(f)
  1114.     print 'From:', m.getaddr('from')
  1115.     print 'To:', m.getaddrlist('to')
  1116.     print 'Subject:', m.getheader('subject')
  1117.     print 'Date:', m.getheader('date')
  1118.     date = m.getdate_tz('date')
  1119.     tz = date[-1]
  1120.     date = time.localtime(mktime_tz(date))
  1121.     if date:
  1122.         print 'ParsedDate:', time.asctime(date),
  1123.         hhmmss = tz
  1124.         (hhmm, ss) = divmod(hhmmss, 60)
  1125.         (hh, mm) = divmod(hhmm, 60)
  1126.         print '%+03d%02d' % (hh, mm),
  1127.         if ss:
  1128.             print '.%02d' % ss,
  1129.         
  1130.         print 
  1131.     else:
  1132.         print 'ParsedDate:', None
  1133.     m.rewindbody()
  1134.     n = 0
  1135.     while f.readline():
  1136.         n += 1
  1137.     print 'Lines:', n
  1138.     print '-' * 70
  1139.     print 'len =', len(m)
  1140.     if 'Date' in m:
  1141.         print 'Date =', m['Date']
  1142.     
  1143.     if 'X-Nonsense' in m:
  1144.         pass
  1145.     
  1146.     print 'keys =', m.keys()
  1147.     print 'values =', m.values()
  1148.     print 'items =', m.items()
  1149.  
  1150.